<template>
  <div class="cyberpunk-chat-wrapper">
    <!-- 扫描线效果 -->
    <div class="cyberpunk-scanline"></div>
    
    <div class="cyberpunk-chat-container">
      <!-- 头部区域 -->
      <div class="cyberpunk-chat-header">
        <div class="cyberpunk-user-info">
          <span class="cyberpunk-username">{{ username }}</span>
          <span class="cyberpunk-status" :class="{ 'online': isOnline, 'offline': !isOnline }"></span>
          <button class="cyberpunk-logout-btn" @click="logout">
            <span class="cyberpunk-button-text">LOGOUT</span>
            <span class="cyberpunk-button-glitch"></span>
          </button>
        </div>
        
        <div class="cyberpunk-chat-title" v-show="chatMes">
          <div class="cyberpunk-title-line"></div>
          <span>CONVERSATION WITH {{ toName }}</span>
          <div class="cyberpunk-title-line"></div>
        </div>
      </div>

      <!-- 主体区域 -->
      <div class="cyberpunk-chat-body">
        <!-- 消息区域 -->
        <div class="cyberpunk-messages" id="messageArea" v-show="isShowChat">
          <div 
            class="cyberpunk-message" 
            v-for="(message, index) in historyMessage" 
            :key="index"
            :class="{
              'guest': message.fromName,
              'host': !message.fromName,
              'animate__animated animate__fadeIn': index === historyMessage.length - 1
            }"
          >
            <div class="cyberpunk-message-content">
              <div class="cyberpunk-message-sender">{{ message.fromName || username }}</div>
              <div class="cyberpunk-message-bubble" :class="message.fromName ? 'guest' : 'host'">
                {{ message.message }}
                <div class="cyberpunk-message-tail"></div>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="cyberpunk-input-area" v-show="isShowChat">
          <textarea
            class="cyberpunk-chat-input"
            v-model="sendMessage.message"
            @keyup.enter="submit"
            placeholder="TYPE YOUR MESSAGE HERE..."
          ></textarea>
          <button class="cyberpunk-send-btn" @click="submit">
            <span class="cyberpunk-button-text">SEND</span>
            <span class="cyberpunk-button-glitch"></span>
          </button>
        </div>

        <!-- 侧边栏 -->
        <div class="cyberpunk-sidebar">
          <!-- 联系人列表 -->
          <div class="cyberpunk-sidebar-section">
            <div class="cyberpunk-sidebar-title">
              <span>CONTACTS</span>
              <div class="cyberpunk-sidebar-line"></div>
            </div>
            <ul class="cyberpunk-contact-list">
              <li 
                class="cyberpunk-contact-item" 
                v-for="(friend, index) in friendsList" 
                :key="index"
                @click="showChat(friend)"
              >
                <span class="cyberpunk-contact-name">{{ friend }}</span>
                <span class="cyberpunk-contact-status"></span>
              </li>
            </ul>
          </div>

          <!-- 系统消息 -->
          <div class="cyberpunk-sidebar-section">
            <div class="cyberpunk-sidebar-title">
              <span>SYSTEM BROADCAST</span>
              <div class="cyberpunk-sidebar-line"></div>
            </div>
            <ul class="cyberpunk-broadcast-list">
              <li 
                class="cyberpunk-broadcast-item" 
                v-for="(name, index) in systemMessages" 
                :key="index"
              >
                <span class="cyberpunk-broadcast-text">USER {{ name }} IS NOW ONLINE</span>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { onMounted, ref, nextTick } from 'vue'
import request from '@/util/request.js'
import { ElMessage } from "element-plus";

export default {
  setup() {
    const webSocket = ref(null)
    const isShowChat = ref(false)
    const chatMes = ref(false)
    const isOnline = ref(true)
    const username = ref('')
    const toName = ref('')
    const sendMessage = ref({
      toName: '',
      message: ''
    })
    const historyMessage = ref([])
    const friendsList = ref([])
    const systemMessages = ref([])

    const init = async () => {
      try {
        const response = await request.get('/user/getUsername')
        if (response.code === 200) {
          username.value = response.data
          initWebSocket()
        }
      } catch (error) {
        console.error('获取用户名失败:', error)
      }
    }

    const initWebSocket = () => {
      webSocket.value = new WebSocket('ws://localhost:8081/chat')
      webSocket.value.onopen = onOpen
      webSocket.value.onmessage = onMessage
      webSocket.value.onclose = onClose
    }

    const logout = async () => {
      try {
        const response = await request.get('/user/logout')
        if (response.code === 200) {
          localStorage.removeItem('token')
          ElMessage.success(response.message)
          setTimeout(() => {
            window.location.href = '/'
          }, 1000)
        }
      } catch (error) {
        console.error('登出失败:', error)
      }
    }

    const onOpen = () => {
      isOnline.value = true
    }

    const onClose = () => {
      isOnline.value = false
    }

    const onMessage = (event) => {
      const response = JSON.parse(event.data)
      console.log('收到消息:', response)

      if (response.system) {
        updateFriendList(response.message)
      } else {
        addMessageToHistory(response)
      }
    }

    const updateFriendList = (names) => {
      friendsList.value = names.filter(name => name !== username.value)
      systemMessages.value = [...friendsList.value]
    }

    const addMessageToHistory = (message) => {
      const historyKey = message.fromName || toName.value
      let history = sessionStorage.getItem(historyKey) || '[]'
      historyMessage.value = JSON.parse(history)
      historyMessage.value.push(message)
      sessionStorage.setItem(historyKey, JSON.stringify(historyMessage.value))
      scrollToBottom()
    }

    const showChat = (name) => {
      toName.value = name
      const history = sessionStorage.getItem(name) || '[]'
      historyMessage.value = JSON.parse(history)
      isShowChat.value = true
      chatMes.value = true
      nextTick(scrollToBottom)
    }

    const submit = () => {
      if (!sendMessage.value.message.trim()) {
        ElMessage.error('请输入消息内容')
        return
      }

      const message = {
        toName: toName.value,
        message: sendMessage.value.message.trim()
      }

      webSocket.value.send(JSON.stringify(message))
      addMessageToHistory({...message, fromName: null})
      sendMessage.value.message = ''
    }

    const scrollToBottom = () => {
      const messageArea = document.getElementById('messageArea')
      if (messageArea) {
        messageArea.scrollTop = messageArea.scrollHeight
      }
    }

    onMounted(init)

    return {
      webSocket,
      isShowChat,
      chatMes,
      isOnline,
      username,
      toName,
      sendMessage,
      historyMessage,
      friendsList,
      systemMessages,
      logout,
      showChat,
      submit
    }
  }
}
</script>

<style scoped>
/* 基础样式 */
.cyberpunk-chat-wrapper {
  position: relative;
  width: 100%;
  height: 100vh;
  background-color: #0a0a0a;
  background-image: 
    linear-gradient(rgba(0, 255, 255, 0.05) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0, 255, 255, 0.05) 1px, transparent 1px);
  background-size: 20px 20px;
  overflow: hidden;
  font-family: 'Courier New', monospace;
  color: #00ffff;
}

.cyberpunk-chat-container {
  position: relative;
  width: 100%;
  height: 100%;
  background: rgba(10, 10, 20, 0.8);
  border: 1px solid rgba(0, 255, 255, 0.3);
  box-shadow: 0 0 20px rgba(0, 255, 255, 0.2);
  display: flex;
  flex-direction: column;
  z-index: 1;
}

/* 头部样式 */
.cyberpunk-chat-header {
  padding: 15px 20px;
  border-bottom: 1px solid rgba(0, 255, 255, 0.3);
  display: flex;
  flex-direction: column;
}

.cyberpunk-user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.cyberpunk-username {
  font-weight: bold;
  text-shadow: 0 0 5px rgba(0, 255, 255, 0.5);
}

.cyberpunk-status {
  width: 10px;
  height: 10px;
  border-radius: 50%;
}

.cyberpunk-status.online {
  background-color: #00ff00;
  box-shadow: 0 0 10px #00ff00;
}

.cyberpunk-status.offline {
  background-color: #ff0000;
  box-shadow: 0 0 10px #ff0000;
}

.cyberpunk-logout-btn {
  margin-left: auto;
  padding: 5px 15px;
  background: transparent;
  border: 1px solid #ff0000;
  color: #ff0000;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
}

.cyberpunk-logout-btn:hover {
  background: rgba(255, 0, 0, 0.1);
  box-shadow: 0 0 10px rgba(255, 0, 0, 0.5);
}

.cyberpunk-chat-title {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
  font-size: 14px;
  color: #6fbdf3;
}

.cyberpunk-title-line {
  flex: 1;
  height: 1px;
  background: linear-gradient(90deg, transparent, #6fbdf3, transparent);
  margin: 0 10px;
}

/* 主体区域 */
.cyberpunk-chat-body {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* 消息区域 */
.cyberpunk-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  scrollbar-width: thin;
  scrollbar-color: #00ffff transparent;
}

.cyberpunk-messages::-webkit-scrollbar {
  width: 5px;
}

.cyberpunk-messages::-webkit-scrollbar-thumb {
  background-color: #00ffff;
  border-radius: 5px;
}

.cyberpunk-message {
  margin-bottom: 20px;
}

.cyberpunk-message.host {
  display: flex;
  justify-content: flex-end;
}

.cyberpunk-message.guest {
  display: flex;
  justify-content: flex-start;
}

.cyberpunk-message-content {
  max-width: 70%;
}

.cyberpunk-message-sender {
  font-size: 12px;
  margin-bottom: 5px;
  color: #00ffff;
  text-shadow: 0 0 5px rgba(0, 255, 255, 0.3);
}

.cyberpunk-message-bubble {
  padding: 10px 15px;
  border-radius: 5px;
  position: relative;
  word-break: break-word;
  line-height: 1.4;
}

.cyberpunk-message-bubble.guest {
  background: rgba(0, 255, 255, 0.1);
  border: 1px solid rgba(0, 255, 255, 0.3);
  color: #00ffff;
  border-top-left-radius: 0;
}

.cyberpunk-message-bubble.host {
  background: rgba(255, 0, 255, 0.1);
  border: 1px solid rgba(255, 0, 255, 0.3);
  color: #ff00ff;
  border-top-right-radius: 0;
}

.cyberpunk-message-tail {
  position: absolute;
  width: 0;
  height: 0;
  top: 0;
}

.cyberpunk-message-bubble.guest .cyberpunk-message-tail {
  left: -10px;
  border-right: 10px solid rgba(0, 255, 255, 0.3);
  border-top: 10px solid transparent;
  border-bottom: 10px solid transparent;
}

.cyberpunk-message-bubble.host .cyberpunk-message-tail {
  right: -10px;
  border-left: 10px solid rgba(255, 0, 255, 0.3);
  border-top: 10px solid transparent;
  border-bottom: 10px solid transparent;
}

/* 输入区域 */
.cyberpunk-input-area {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 15px;
  background: rgba(10, 10, 20, 0.9);
  border-top: 1px solid rgba(0, 255, 255, 0.3);
  display: flex;
  gap: 10px;
}

.cyberpunk-chat-input {
  flex: 1;
  padding: 10px;
  background: transparent;
  border: 1px solid rgba(0, 255, 255, 0.3);
  color: #00ffff;
  font-family: 'Courier New', monospace;
  resize: none;
  outline: none;
  min-height: 60px;
  max-height: 120px;
}

.cyberpunk-chat-input:focus {
  border-color: #00ffff;
  box-shadow: 0 0 10px rgba(0, 255, 255, 0.3);
}

.cyberpunk-send-btn {
  padding: 0 20px;
  background: transparent;
  border: 1px solid #00ffff;
  color: #00ffff;
  font-family: 'Courier New', monospace;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
}

.cyberpunk-send-btn:hover {
  background: rgba(0, 255, 255, 0.1);
  box-shadow: 0 0 10px rgba(0, 255, 255, 0.5);
}

/* 侧边栏 */
.cyberpunk-sidebar {
  width: 250px;
  border-left: 1px solid rgba(0, 255, 255, 0.3);
  background: rgba(10, 10, 20, 0.7);
  overflow-y: auto;
}

.cyberpunk-sidebar-section {
  padding: 15px;
  border-bottom: 1px solid rgba(0, 255, 255, 0.2);
}

.cyberpunk-sidebar-title {
  font-size: 14px;
  margin-bottom: 10px;
  color: #00ffff;
}

.cyberpunk-sidebar-line {
  height: 1px;
  background: linear-gradient(90deg, transparent, #00ffff, transparent);
  margin-top: 5px;
}

.cyberpunk-contact-list, .cyberpunk-broadcast-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.cyberpunk-contact-item, .cyberpunk-broadcast-item {
  padding: 8px 0;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cyberpunk-contact-item:hover {
  background: rgba(0, 255, 255, 0.1);
}

.cyberpunk-contact-name {
  font-size: 13px;
}

.cyberpunk-contact-status {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #00ff00;
  margin-left: 5px;
  box-shadow: 0 0 5px #00ff00;
}

.cyberpunk-broadcast-item {
  font-size: 12px;
  color: #ff00ff;
  padding: 5px 0;
}

.cyberpunk-broadcast-text {
  display: block;
  padding: 5px;
  background: rgba(255, 0, 255, 0.05);
  border-left: 2px solid #ff00ff;
}

/* 扫描线效果 */
.cyberpunk-scanline {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    to bottom,
    transparent 0%,
    rgba(0, 255, 255, 0.05) 50%,
    transparent 100%
  );
  animation: scan 8s linear infinite;
  z-index: 0;
  pointer-events: none;
}

@keyframes scan {
  0% { transform: translateY(-100%); }
  100% { transform: translateY(100%); }
}

/* 按钮特效 */
.cyberpunk-button-text {
  position: relative;
  z-index: 1;
}

.cyberpunk-button-glitch {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(45deg, 
    transparent 45%, 
    #ff00ff 45%, 
    #ff00ff 55%, 
    transparent 55%);
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: 0;
}

.cyberpunk-logout-btn:hover .cyberpunk-button-glitch,
.cyberpunk-send-btn:hover .cyberpunk-button-glitch {
  opacity: 0.3;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .cyberpunk-sidebar {
    width: 200px;
  }
}

@media (max-width: 576px) {
  .cyberpunk-chat-body {
    flex-direction: column;
  }
  
  .cyberpunk-sidebar {
    width: 100%;
    border-left: none;
    border-top: 1px solid rgba(0, 255, 255, 0.3);
    max-height: 150px;
  }
  
  .cyberpunk-message-content {
    max-width: 85%;
  }
}
</style>